package com.pap.gateway.dynamicrouter.router;

import com.pap.obj.vo.response.ResponseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.util.List;

@Service
public class DynamicRouteServiceImpl implements ApplicationEventPublisherAware {

    private static Logger logger  =  LoggerFactory.getLogger(DynamicRouteServiceImpl.class);

    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher publisher;

    /**
     * 更新路由
     * @param definitionList
     * @return
     */
    public ResponseVO<String> update(List<RouteDefinition> definitionList) {
        if(definitionList != null) {
            for(RouteDefinition definition : definitionList) {
                try {
                    this.routeDefinitionWriter.delete(Mono.just(definition.getId()));
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                try {
                    routeDefinitionWriter.save(Mono.just(definition)).subscribe();
                    this.publisher.publishEvent(new RefreshRoutesEvent(this));
                } catch (Exception e) {
                    logger.error("DynamicRouteServiceImpl.update.动态路由更新失败: [{}]", e.getMessage());
                }
            }
        }
        return ResponseVO.successdata("success");
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

}
